import { Button, Snackbar, TextField } from "@material-ui/core";
import { Alert } from "@mui/material";
import React, { FC, MutableRefObject, ReactElement, useRef, useState } from "react";
import { TransitTimeInfo } from "../../../types";
import "./index.css";
import _ from "lodash";

interface IAddBar{
  addTransitTime:(item:TransitTimeInfo)=>void
} 

const AddBar: FC<IAddBar> = ({
  addTransitTime,
}): ReactElement => {
  var originRef = useRef<HTMLInputElement>();
  const [origin, setOrigin] = useState<number>();
  var timeRef = useRef<HTMLInputElement>();
  var destinationRef = useRef<HTMLInputElement>();

  const [errorOpen, setErrorOpen] = useState<boolean>(false);
  const [message, setMessage] = useState<string>();



  const add = (): void => {
    var origin = originRef.current!.value.trim();
    var destination = destinationRef.current!.value.trim();
    var time = timeRef.current!.value.trim();
    if (!origin || origin.length === 0) {
      setMessage("Please input origin.");
      setErrorOpen(true);
      return;
    }
    if (!destination || destination.length === 0) {
      setMessage("Please input destination.");
      setErrorOpen(true);
      return;
    }
    if (!time || time.length === 0) {
      setMessage("Please input time.");
      setErrorOpen(true);
      return;
    }

    var item: TransitTimeInfo = {
      id: _.uniqueId("new_"),
      origin,
      destination,
      estimatedtransittime: _.toNumber(time),
    };
    addTransitTime(item);
    originRef.current!.value = "";
    destinationRef.current!.value = "";
    timeRef.current!.value = "";
  };

  const handleCloseError = () => {
    setErrorOpen(false);
  };
  return (
    <>
      <div className="container">
        <div className="add-container" >
          <TextField label="origin" variant="standard" inputRef={originRef} />
          &nbsp;&nbsp;
          <TextField label="destination" variant="standard" inputRef={destinationRef} />
          &nbsp;&nbsp;
          <TextField label="time" variant="standard" inputRef={timeRef} />
          <Button variant="contained" color="primary" onClick={add}>
            Add
          </Button>
        </div>
      </div>

      <Snackbar
        open={errorOpen}
        autoHideDuration={2000}
        onClose={handleCloseError}
      >
        <Alert severity="error" sx={{ width: "100%" }}>
          {message}
        </Alert>
      </Snackbar>
    </>
  );
};
export default AddBar;
